package com.reverie.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.reverie.common.pojo.CommonPageReq;
import com.reverie.common.pojo.CommonResult;
import com.reverie.dto.req.CouponQueryParam;
import com.reverie.entity.Coupon;
import com.reverie.service.ICouponService;
import com.reverie.util.RandomUtil;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Rui.Zhou
 * @since 2024-02-03
 */
@RestController
@RequestMapping("/coupon")
public class CouponController {
    private static final DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    @Resource
    private ICouponService couponService;


    @PostMapping("bind")
    public CommonResult<Boolean> bind(@RequestBody Coupon coupon) {
        return CommonResult.data(couponService.bind(coupon));
    }

    @PostMapping("queryById")
    public CommonResult<Coupon> queryById(@RequestBody CouponQueryParam queryParam) {
        return CommonResult.data(couponService.getByCouponId(queryParam.getCouponId()));
    }

    @PostMapping("queryPage")
    public CommonResult<Page<Coupon>> queryPage(@RequestBody CommonPageReq<CouponQueryParam> queryPageParam) {
        return CommonResult.data(couponService.queryPage(queryPageParam));
    }

    @PostMapping("save")
    public CommonResult<Boolean> onSave(@RequestBody Coupon coupon) {

        if (coupon.getCpId() == null) {
            boolean isOk = false;
            List<Coupon> couponList = new ArrayList<>();
            if (coupon.getGenerateNum() >= 1) {
                Map<String,String> couponMap = new HashMap<>();
                for (int i = 0; i < coupon.getGenerateNum(); i++) {
                    Coupon couponItem = new Coupon();
                    couponItem.setType("金额");
                    couponItem.setValue(coupon.getValue());
                    couponItem.setName(coupon.getName());
                    couponItem.setCouponDesc(coupon.getCouponDesc());
                    LocalDateTime endDateTime = LocalDateTime.parse(coupon.getExpiresEndTime(), df);
                    LocalDateTime startDateTime = LocalDateTime.parse(coupon.getExpiresStartTime(), df);
                    couponItem.setExpiresEnd((int) endDateTime.toEpochSecond(ZoneOffset.of("+8")));
                    couponItem.setExpiresStart((int) startDateTime.toEpochSecond(ZoneOffset.of("+8")));
                    if (!StringUtils.hasLength(coupon.getCouponId())) {
                        String couponId = getCouponId(coupon.getStartChar(), couponMap);
                        couponItem.setCouponId(couponId);
                    } else {
                        couponItem.setCouponId(coupon.getCouponId());
                    }
                    couponItem.setUserId(null);
                    couponItem.setState(true);
                    couponItem.setIsUsed(Boolean.FALSE);
                    couponItem.setLimitTimes(1);
                    couponList.add(couponItem);
                }
            }
            if (!CollectionUtils.isEmpty(couponList)) {
                isOk = couponService.saveBatch(couponList);
            }
            return CommonResult.data(isOk);
        } else {
            LocalDateTime endDateTime = LocalDateTime.parse(coupon.getExpiresEndTime(), df);
            LocalDateTime startDateTime = LocalDateTime.parse(coupon.getExpiresStartTime(), df);
            coupon.setExpiresEnd((int) endDateTime.toEpochSecond(ZoneOffset.of("+8")));
            coupon.setExpiresStart((int) startDateTime.toEpochSecond(ZoneOffset.of("+8")));
            coupon.setModifiedAt((int) (System.currentTimeMillis() / 1000));
            return CommonResult.data(couponService.saveOrUpdate(coupon));
        }
    }

    @PostMapping("review")
    public CommonResult<Boolean> review(@RequestBody Coupon coupon) {
        Coupon reviewCoupon = couponService.getById(coupon.getCpId());
        reviewCoupon.setModifiedAt((int) (System.currentTimeMillis() / 1000));
        reviewCoupon.setState(coupon.getState());
        return CommonResult.data(couponService.updateById(reviewCoupon));
    }

    @PostMapping("delete")
    public CommonResult<Boolean> delete(@RequestBody Coupon coupon) {
        return CommonResult.data(couponService.removeById(coupon.getCpId()));
    }

    private String getCouponId(String startChar, Map<String,String> couponMap){
        String couponId = RandomUtil.generate(startChar);
        if(!couponMap.containsKey(couponId)){
            couponMap.put(couponId,couponId);
            return couponId;
        }
        return getCouponId(startChar,couponMap);
    }
}
